package com.dhecp.core.utils.qywx;

import com.alibaba.fastjson.JSONObject;
import com.dhecp.framework.util.IX509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName HttpUtils 企业微信HTTP工具类
 * @Description TODO
 * @Author alula
 * @Date 2022-03-02 11:23
 */
public class QyWxHttpUtils {
    private static final Logger logger = LoggerFactory.getLogger(QyWxHttpUtils.class);

    public static JSONObject sendGet(String url) {
        JSONObject jsonObject = null;
        jsonObject = httpRequest(url, "GET", null);
        return jsonObject;
    }

    public static JSONObject sendPost(String url) {
        JSONObject jsonObject = null;
        jsonObject = httpRequest(url, "POST", null);
        return jsonObject;
    }

    public static JSONObject sendPost(String url, String output) {
        JSONObject jsonObject = null;
        jsonObject = httpRequest(url, "POST", output);
        return jsonObject;
    }

    private static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        try {
            logger.debug("【企业微信HTTP】", "http请求request:{},method:{},output{}", new Object[]{requestUrl, requestMethod, outputStr});
            // 创建SSLContext对象，并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new IX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setUseCaches(false);
            connection.setRequestMethod(requestMethod);
            if (outputStr != null) {
                OutputStream out = connection.getOutputStream();
                out.write(outputStr.getBytes("UTF-8"));
                out.close();
            }
            inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                buffer.append(line);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            connection.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (Exception e) {
            logger.error("【企业微信HTTP】", "http请求error:{}", new Object[]{e.getMessage()});
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (inputStreamReader != null) {
                    inputStreamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }

            } catch (ConnectException ce) {
                logger.error("【企业微信HTTP】", "http请求ConnectException:{}", new Object[]{ce.getMessage()});
            }catch (Exception ex) {
                ex.printStackTrace();
                logger.error("【企业微信HTTP】", "http请求Exception:{}", new Object[]{ex.getMessage()});
            }
        }
        return  jsonObject;
    }
}
